package com.martin.lib_base.ktx

import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout

fun ViewPager2.bindTabLayout(tabLayout: TabLayout) {
    val vp = this
    tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
        override fun onTabSelected(tab: TabLayout.Tab?) {
            if (vp.currentItem != tabLayout.selectedTabPosition) {
                vp.currentItem = tabLayout.selectedTabPosition
            }
        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {}
        override fun onTabReselected(tab: TabLayout.Tab?) {}
    })

    vp.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            if (tabLayout.selectedTabPosition != position) {
                tabLayout.selectTab(tabLayout.getTabAt(position))
            }
        }
    })
}